local ffi = require "ffi"
ffi.cdef[[
typedef long long GoInt64;
typedef GoInt64 GoInt;
extern void GetOnlyAudioTsPackage(GoInt p0);
]]
rpmt = ffi.load("rpmt.so")
--为了减少文件名重复，增加一个随机数
math.randomseed(os.time())

function file_exists(path)
  local file = io.open(path, "rb")
  if file then file:close() end
  return file ~= nil
end
ngx.update_time()
--设定临时文件的目录，设置在tmp目录下，可以随时的进行清理
tPath = "/tmp/vdisk_aac/"
if file_exists(tPath) == false
then
   os.execute("mkdir -p "..tPath)
end
local bt = ngx.now()*1000
ngx.log(ngx.DEBUG, "begin:", bt)

local base_m3u8_url = ngx.var.uri:gsub("audio", "hls")
local base_ts_url = base_m3u8_url:gsub("aac", "ts")
local res = ngx.location.capture(base_ts_url)
--#把内空写入到本地文件中，因为不知道如何与go的动态库交换字符串信息，所以暂时先把内容落盘，以文件方式进行处理
ngx.update_time()
local ct = ngx.now()*1000
ngx.log(ngx.DEBUG, "ct:", ct)
local filename = tPath..tostring(ct)..".tmp"
ngx.log(ngx.DEBUG, "filename:"..filename)
local file = io.open(filename, "wb");
file:write(res.body)
file:close()
rpmt.GetOnlyAudioTsPackage(ct)
local file1 = io.open(filename..".1", "r")
local nbody = file1:read("*a")
file1:close()
os.remove(filename)
os.remove(filename..".1")
ngx.print(nbody)
ngx.update_time()
local et = ngx.now()*1000
ngx.log(ngx.DEBUG, "end:", et)
ngx.exit(ngx.HTTP_OK)

